package com.example.springbootmqdemo.ackservice;

import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * Classname: MQOrderService
 *
 * @Author: Jam
 * @Create 2022/11/29 - 19:16
 * @Version 1.0
 */
@Service
//可靠消息发送消息
public class MQOrderService {
    @Autowired
    RabbitTemplate rabbitTemplate;

    public void createOreder(String msg) throws Exception{
        //1 .订单信息插入订单库 此处省略逻辑
        this.saveOrder(msg);

        //2 .发送消息到MQ
        this.sendMQ(msg);
    }

    //正常下单逻辑不变
    private void saveOrder(String msg) {
        System.out.println("插入订单信息：-------------->" + msg);
        //消息冗余 保存消息到本地
        System.out.println("保存消息到本地：-------------->" + msg);
        //2.发送订单信息到配送系统 此处省略逻辑
        this.sendOrder(msg);
    }

    private void sendOrder(String msg) {
        System.out.println("订单已生成，配送中：-------------->" + msg);
    }

    private void sendMQ(String msg) {
        String exchangeName = "ACK_fanout_exchange";
        String routeKey = "";
        rabbitTemplate.convertAndSend(exchangeName, routeKey, msg,new CorrelationData(msg));
    }


    //PostConstruct修饰静态void方法 用来在加载servlet时运行 只会在构造函数之后到init前 执行一次
    @PostConstruct
    public void regCallBack(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("cause"+cause);
                String  orderId = correlationData.getId();
                if(!ack){
                    System.out.println("mq应答失败！");
                    return;
                }
                try{
                    //修改冗余表status字段
                    // int count = mapper.update（update table set status =1 where orderId = ？ ）
                    int count = 1;
                    if(count == 1){
                        System.out.println("本地status修改成功，消息已投递到mq！");
                    }
                }catch (Exception e){
                    System.out.println("本地status修改失败"+e.getMessage());
                }
            }
        });
    }
}
